package lgkj.meicqt20.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * com.example.hjx.autostart Created by hjx on 2017/5/8 20:53
 *
 * @Company:
 * @Description: ${TODO}
 * @Email:1263276841@qq.com
 * @Version $Rev$
 * @UpdateAuthor $Author$ on 2017/5/8$
 * @UpdateDes ${TODO}
 */

public class TimerService extends Service {
    private String TAG = "TimerService";
    //    private String className = "com.example.hjx.sda.ClientActivity";
    private String pageName = "lgkj.meicqt20";
    private String className = "lgkj.meicqt20.ui.StartActivity";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"onStartCommand");
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (!isTop(TimerService.this)) {
                    openCLD(pageName, TimerService.this);
                }
            }
        }, 20 * 1000, 60 * 1000);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"onCreate");
    }

    public boolean isTop(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            Log.i(TAG, topActivity.getPackageName());
            if (topActivity.getPackageName().equals(pageName)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    public void openCLD(String packageName, Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName cn = new ComponentName(packageName, className);
        intent.setComponent(cn);
        startActivity(intent);
        Log.i(TAG, "启动界面" + packageName);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "service 关闭了~");
    }
}
